package com.egame.manage.biz.web.controller.gc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.egame.client.biz.EGameClientBiz;
import cn.egame.common.model.PageData;
import cn.egame.common.servlet.WebUtils;
import cn.egame.common.util.Utils;
import cn.egame.ext.cu.ManufactureInfo;
import cn.egame.interfaces.EnumType.AppParameterType;
import cn.egame.interfaces.gc.TerminalInfo;
import cn.egame.interfaces.pu.AppParameter;

import com.egame.manage.biz.domain.TerminalBean;
import com.egame.manage.biz.domain.TerminalGroupInfoBean;
import com.egame.manage.biz.server.ManageClient;
import com.egame.manage.biz.server.ManageClientExt;
import com.egame.manage.biz.server.cu.ManufacturerServiceImpl;
import com.egame.manage.biz.server.gc.TerminalGroupServiceImpl;
import com.egame.manage.biz.server.gc.TerminalServiceImpl;
import com.egame.manage.biz.server.pu.ParameterServiceImpl;
import com.egame.manage.biz.utils.ConstVar;
import com.egame.manage.biz.web.controller.BaseController;
import com.lenovo.manager.business.domain.UserBean;
@Controller
@RequestMapping("/tv/terminalgroup")
public class TerminalGroupController extends BaseController {
	public TerminalGroupController(){		
	}
	public TerminalGroupController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}
	@RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView showList(HttpServletRequest req, HttpServletResponse resp) throws Exception{		
		int page = WebUtils.getInt(req, "page",0);
		int rowsOfPage = WebUtils.getInt(req, "rowsOfPage",15);		
		String name = WebUtils.getString(req, "terminalGroupName", "");
		ModelAndView mav = new ModelAndView("/new/op/terminalGroupList");
		
		PageData pd 
			= TerminalGroupServiceImpl.getInstance().pageTerminalGroupIds(appId, loginUserId, name, page, rowsOfPage);
		mav.addObject("pd", pd);		
		mav.addObject("terminalGroupName", name);
		mav.addObject("pdUrl", "/tv/terminalgroup/list");
		
		return mav;
	}	

	@RequestMapping(value = "/set/show", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView showNewPage(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int manufactureId = WebUtils.getInt(req, "manufacturerid", 0);
		String shortUa = WebUtils.getString(req, "shortUa","");
		String uacode = WebUtils.getString(req, "uacode","");
		String screenpx = WebUtils.getString(req, "screenpx", "");
		TerminalInfo beanInfo = new TerminalInfo();
		beanInfo.setManufacturerId(manufactureId);    
		beanInfo.setShortUA(shortUa);
		beanInfo.setUACode(uacode);
		beanInfo.setScreenPx(screenpx);
		ModelAndView mav = new ModelAndView("/new/op/newTerminalGroup");		
		
		List<Integer> ids = TerminalServiceImpl.getInstance().listTerminalIdsByGroupId(0);
		Set<TerminalInfo> terminalInfoList = new HashSet<TerminalInfo>(
				ManageClient.getInstance().listTerminalInfoByIds(appId, loginUserId, ids));
		
		req.setAttribute("terminalInfoList", terminalInfoList);
		List<String[]> brandList = ManufacturerServiceImpl.getInstance().listManufacturerBand(appId, loginUserId);
		mav.addObject("brandList", brandList);
		
		return mav;
	}

	@RequestMapping(value = "/set", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView set(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		if (req.getSession().getAttribute(
				com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null) {
			UserBean userBean = (UserBean) req.getSession().getAttribute(
					com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}

		String name = WebUtils.getString(req, "name", "");
		String remark = WebUtils.getString(req, "remark", "");
		String relatedIds = req.getParameter("relatedIds");
		String[] toTerminalIds = null;
		// 修改机型组中机型信息后关联的机型信息,格式为"1,2,3"
		if (relatedIds != null) {
			toTerminalIds = Utils.toArrayString(relatedIds);
		}
		AppParameter app = new AppParameter();
		app.setOperatorId((int) loginUserId);
		int maxSortNo = ParameterServiceImpl.getInstance().getMaxSortNo(
				ConstVar.APP_TERMINAL_GROUP);
		app.setName(name);
		app.setSort(1 + maxSortNo);
		app.setType(AppParameterType.all);// TODO
		app.setEnable(true);
		app.setDepth(2);
		app.setParentId(ConstVar.APP_TERMINAL_GROUP);
		app.setRemark(remark);
		int groupId = ManageClient.getInstance().setAppParameter(appId,
				loginUserId, app);
		if (groupId > 0 && toTerminalIds != null && toTerminalIds.length > 0) {
			TerminalGroupServiceImpl.getInstance().updateTerminalGroupId(
					toTerminalIds, groupId);
		}

		return showList(req, resp);
	}
	
	@RequestMapping(value = "/update", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView update(TerminalBean bean,HttpServletRequest req, HttpServletResponse resp) throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}		
		int groupId = WebUtils.getInt(req, "id", 0);
		String name = WebUtils.getString(req, "name", "");
		String remark = WebUtils.getString(req, "remark", "");
		//修改机型组中机型信息后关联的机型信息,格式为"2,1,3"
		String relatedIds = req.getParameter("relatedIds");
		
		//判断下是否修改机型组,及其对应的机型组信息  //not do
		//[1,2,3]
		/*
		List<Integer> terminalIdsRelatedPre = TerminalServiceImpl.getInstance().
				listTerminalIdsByGroupId(groupId);
		AppParameter appPre = ManageClient.getInstance().getAppParameterById(appId, loginUserId, groupId);
		if(relatedIds!=null){
			int[] ids = Utils.toArrayInt((relatedIds));
			Arrays.sort(ids);
			System.out.println(Utils.toString(ids));
			System.out.println(Utils.toString(terminalIdsRelatedPre));
			if(Utils.toString(ids).equals(Utils.toString(terminalIdsRelatedPre))
					&& appPre.getName().equals(name)
					&& appPre.getRemark().equals(remark)){
				return showList(req,resp);
			}
		}
		*/
		
		String[] toTerminalIds = null;
		if(relatedIds != null){
			toTerminalIds = Utils.toArrayString(relatedIds);
			TerminalGroupInfoBean terminalGroupInfoBean = new TerminalGroupInfoBean(groupId, name, remark);
			TerminalGroupServiceImpl.getInstance().updateTerminalGroupInfo(appId, loginUserId, terminalGroupInfoBean, toTerminalIds);
		}
		
		return showList(req,resp);
	}

	@RequestMapping(value = "/update/show", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView editTerminalGroup(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		int groupId = WebUtils.getInt(req, "id", 0);
		ModelAndView mav = new ModelAndView("/new/op/editTerminalGroup");		
		List<String[]> brandList = ManufacturerServiceImpl.getInstance().listManufacturerBand(appId, loginUserId);
		mav.addObject("brandList", brandList);
		
		TerminalGroupInfoBean bean = TerminalGroupServiceImpl.getInstance().
				getTerminalGroupInfoById(appId,loginUserId,groupId);
		mav.addObject("terminalGroupInfoBean",bean);
		List<Integer> terminalIdsRelated = TerminalServiceImpl.getInstance().
				listTerminalIdsByGroupId(groupId);
		Set<TerminalInfo> terminalInfoListRelated = new HashSet<TerminalInfo>(ManageClient.getInstance()
				.listTerminalInfoByIds(appId, loginUserId, terminalIdsRelated));
		List<Integer> terminalIds = TerminalServiceImpl.getInstance().
				listTerminalIdsByGroupId(0);
		Set<TerminalInfo> terminalInfoList = new HashSet<TerminalInfo>(ManageClient.getInstance()
				.listTerminalInfoByIds(appId, loginUserId, terminalIds));
		
		req.setAttribute("terminalInfoList", terminalInfoList);
		req.setAttribute("terminalInfoListRelated", terminalInfoListRelated);
		return mav;
	}
	
	@RequestMapping(value = "/delete", method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView deleteTerminalGroup(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}
		int groupId = WebUtils.getInt(req, "id",0);
		if(groupId != 0){
			TerminalGroupServiceImpl.getInstance().deleteTerminalGroup(groupId);
		}
		return showList(req,resp);
	}
	
	
	/** 查询组名是否已经存在 */
	@RequestMapping(value = "/checkExist", method = {RequestMethod.POST})
	@ResponseBody
	public Object checkTerminalGroupNameExist(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String name = WebUtils.getString(req, "name",null);
		int id = WebUtils.getInt(req, "id", 0);
		int num = 0;
		if(name!=null){
			num = TerminalGroupServiceImpl.getInstance().checkTerminalGroupNameExist(id, name);
		}
		String exist = num>0 ? "exist" : "notExist";
		
		map.put("exist", exist);
		map.put("retCode", "success");
		return map;
	}
	
	/** 机型组详情信息 */
	@RequestMapping(value = "/detail", method = {RequestMethod.POST})
	@ResponseBody
	public Object terminalGroupDetail(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		if(req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY) != null){
			UserBean userBean = (UserBean) req.getSession().getAttribute(com.egame.manage.biz.utils.ConstVar.USER_SESSION_KEY);
			loginUserId = userBean.getOperatorId();
		}		
		int groupId = WebUtils.getInt(req, "id", 0);
		TerminalGroupInfoBean terminalGroupInfoBean = 		
				TerminalGroupServiceImpl.getInstance().getTerminalGroupInfoById(appId, loginUserId, groupId);
		
		List<Integer> ids = TerminalServiceImpl.getInstance().listTerminalIdsByGroupId(groupId);
		List<TerminalInfo> terminalInfos = ManageClient.getInstance().listTerminalInfoByIds(appId, loginUserId, ids);
		
		map.put("terminalGroupInfoBean", terminalGroupInfoBean);
		map.put("terminalInfos", terminalInfos);
		map.put("retCode", "success");
		return map;
	}
}
